//
//  LZFAllVC.m
//  LZFBuDieJie
//
//  Created by 梁梓烽 on 16/6/25.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//
/*
 此类主要是 不用mjrefresh来实现上拉动,下拉刷新时候的代码
 方便以后复习用
 
 
 */
#import "LZFAllVC.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <SVProgressHUD.h>
#import "LZFTopicItem.h"
#import "LZFTopicCell.h"
#import <UIImageView+WebCache.h>



@interface LZFAllVC ()
@property(nonatomic,weak)UILabel *updateLabel;
@property(nonatomic,weak)UILabel *loadLabel;
@property(nonatomic,assign,getter=isHeaderFresh)BOOL headerFresh;
@property(nonatomic,assign,getter=isFooterFresh)BOOL footerFresh;
@property(nonatomic,weak)AFHTTPSessionManager *manager;
@property(nonatomic,strong)NSString *maxtime;
@property(nonatomic,strong)NSMutableArray *topicItemArray;



@end

@implementation LZFAllVC
static NSString  *const ID=@"cell";
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //设置tableview 注意这里的顺序问题,一定要先设置了tableview的topinsets先,再调用beginHeaderFresh
    [self setUpTableView];

      //设置刷新控件
    [self setUpFresh];
    
    //程序一开始就开始下拉刷新
    [self beginHeaderFresh];

  
    //注册监听
    [self setUpNote];
    
 
//    
//    NSLog(@"%@66666",NSStringFromUIEdgeInsets(self.tableView.contentInset));
//    NSLog(@"tableviewtopinsets%f66666",self.tableView.contentInset.top);
}

-(void)setUpTableView
{
    //设置tableview的背景颜色
    self.view.backgroundColor=LZFGlobalColor;
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZFTopicCell class]) bundle:nil] forCellReuseIdentifier:ID];
    
    //设置tableview全屏穿透,
    self.tableView.contentInset=UIEdgeInsetsMake(LZFNavMaxY+LZFTitleViewH, 0, LZFTabBarMaxH, 0);
    self.tableView.scrollIndicatorInsets=self.tableView.contentInset;
    //取消分割线
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
}

#pragma mark 注册监听
-(void)setUpNote
{
    
    //注册监听 tabbarbutton重复点击的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tabBarButtonDidRepeatClicked) name:LZFTabBarButtonDidRepeatClickedNotification object:nil];
    
    //注册监听  titlebutton重复点击的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(titleButtonDidClicked) name:LZFTitleButtonDidClickedNotification object:nil];
    
}

#pragma mark 通知触发

-(void)titleButtonDidClicked
{
    
    //限制选中的是精华控制器才可以通过
    if (self.view.window==nil) return;
    
    //限制选中的是全部模块的才可以通过
    UIScrollView *scrollView=self.view;
    if (scrollView.scrollsToTop==NO)return;
    
    //开始下拉更新数据
    [self beginHeaderFresh];
}


-(void)tabBarButtonDidRepeatClicked
{
    [self titleButtonDidClicked];
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark AFHTTPSessionManager懒加载
-(AFHTTPSessionManager *)manager
{
    if (_manager==nil) {
        _manager=[AFHTTPSessionManager manager];
    }
    return  _manager;
}


//设置刷新控件f
-(void)setUpFresh
{
    //下拉刷新label
    UILabel *updateLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, -50, screenW, 50)];
    self.updateLabel=updateLabel;
    updateLabel.backgroundColor=[UIColor redColor];
    updateLabel.text=@"下拉可刷新";
    updateLabel.textAlignment=NSTextAlignmentCenter;
    //updateLabel.frame=;
    [self.tableView addSubview:updateLabel];
    
    //广告label
    UILabel *adLabel=[[UILabel alloc]init];
    adLabel.backgroundColor=[UIColor grayColor];
    adLabel.text=@"广告......";
    adLabel.textAlignment=NSTextAlignmentCenter;
    adLabel.frame=CGRectMake(0, 0, 0, 35);
    self.tableView.tableHeaderView=adLabel;
    
    //上拉动刷新label
    UILabel *loadLabel=[[UILabel alloc]init];
    loadLabel.backgroundColor=[UIColor redColor];
    loadLabel.text=@"上拉加载更多数据....";
    loadLabel.textAlignment=NSTextAlignmentCenter;
    loadLabel.frame=CGRectMake(0, 0, 0, 35);
    self.loadLabel=loadLabel;
    self.tableView.tableFooterView=loadLabel;

}

#pragma mark  scrollviewdelegate

//监听scrollview滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%@",NSStringFromCGPoint(scrollView.contentOffset));
    [self handleHeader];
    
    [self handleFooter];
    
    //在滚动过程中清除缓存
    [[SDImageCache sharedImageCache]clearMemory];
}

//监听scrollview拖拽
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    if (self.isHeaderFresh) return;
    
    CGFloat offset = -(self.tableView.contentInset.top+self.updateLabel.xmg_height);
    
    if (self.tableView.contentOffset.y<offset) {
        //开始下拉刷新
        
        [self beginHeaderFresh];
    }
    
    
}

//处理头部
-(void)handleHeader
{
    if (self.updateLabel==nil) return;
    
    if (self.isHeaderFresh) return;
    
    
 
   CGFloat offset = -(self.tableView.contentInset.top+self.updateLabel.xmg_height);
   
    if (self.tableView.contentOffset.y<offset) {
        self.updateLabel.backgroundColor=[UIColor purpleColor];
        self.updateLabel.text=@"松开马上刷新";
    }
    else
    {
        self.updateLabel.backgroundColor=[UIColor redColor];
        self.updateLabel.text=@"下拉可刷新";
    }
}



//开始头部刷新
-(void)beginHeaderFresh
{
    //控制上拉,下拉不共存,想象成开关即可
    
    if (self.isFooterFresh) return;
    //如果正在处于刷新状态,返回
    if (self.isHeaderFresh) return;
    
    //修改刷新转改为yes
    self.headerFresh=YES;
    
    //修改updateLabel的样式和contentInset
    self.updateLabel.backgroundColor=[UIColor blueColor];
    self.updateLabel.text=@"正在刷新最新数据";
    [UIView animateWithDuration:1.0 animations:^{
        
        //LZFLog(@"top%f",self.tableView.contentInset.top);
        UIEdgeInsets edge =  self.tableView.contentInset;
        edge.top+=self.updateLabel.xmg_height; //99+50
        self.tableView.contentInset=edge;
        
        //这三句,重复点击tababrbutton/点击cell实现刷新,确保header能掉下来,直接设置offset.y=-149
        CGPoint offset= self.tableView.contentOffset;
        offset.y=-edge.top;
        self.tableView.contentOffset=offset;
        
    }];
    
    //加载最新数据
    [self loadNewToPic];
}



//帖子类型
-(NSInteger)type
{
    return LZFTopicTypeAll;
}

//加载新的数据
-(void)loadNewToPic
{
    //每次发送请求时,都停止之前的task
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //http://api.budejie.com/api/api_open.php?a=list&c=data
    NSMutableDictionary *dic=[NSMutableDictionary new];
    dic[@"a"]=@"list";
    dic[@"c"]=@"data";
    dic[@"type"]=@([self type]);

    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
       LZFAFNWriteToPlist(@"dd")
        //获取maxtime,拿到上次请求数据的maxtime.用于下次发送请求发送给服务器,返回下一页的数据
        NSString *maxtime = responseObject[@"info"][@"maxtime"];
        self.maxtime=maxtime;
        
        NSMutableArray *array=responseObject[@"list"];
        
        //字典数组转模型数组
       self.topicItemArray=[LZFTopicItem mj_objectArrayWithKeyValuesArray:array];
        
        //刷新tableview
        [self.tableView reloadData];
        
        //结束头部刷新
        [self endHeaderFresh];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束头部刷新
        [self endHeaderFresh];
        
        // 如果是因为取消任务来到failure这个block, 就直接返回, 不需要提醒错误信息
        if (error.code == NSURLErrorCancelled) return;
        
        // 请求失败的提醒
        [SVProgressHUD showErrorWithStatus:@"网络繁忙,请稍后再试!"];

    }];
    
}

//结束头部刷新
-(void)endHeaderFresh
{
    self.headerFresh=NO;
    [UIView animateWithDuration:1.0 animations:^{
        //LZFLog(@"top%f",self.tableView.contentInset.top);
        UIEdgeInsets edge =  self.tableView.contentInset;
        edge.top-=self.updateLabel.xmg_height; //弹回去
        self.tableView.contentInset=edge;

    }];
    
}


//处理尾部控件
-(void)handleFooter
{
    if (self.topicItemArray.count==0) return;
    if (self.isFooterFresh) return;
    
    CGFloat offset = self.tableView.contentSize.height+self.tableView.contentInset.bottom-self.tableView.xmg_height;
    
    if (self.tableView.contentOffset.y>=offset) {
        //开始上拉刷新,加载更多数据
        [self beginFooterFresh];
    }
}

//开始尾部刷新
-(void)beginFooterFresh
{

    if (self.isHeaderFresh) return;
    if (self.isFooterFresh) return;
    
    self.footerFresh=YES;
    
    self.loadLabel.backgroundColor=[UIColor blueColor];
    self.loadLabel.text=@"正在加载更多的数据....";
    
    [self loadMoreTopic];
    
}


//上拉加载更多的数据
-(void)loadMoreTopic
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSMutableDictionary *dic=[NSMutableDictionary new];
    dic[@"a"]=@"list";
    dic[@"c"]=@"data";
    dic[@"type"]=@([self type]);
    dic[@"maxtime"]=self.maxtime;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php"parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        //获取maxtime,拿到上次请求数据的maxtime.用于下次发送请求发送给服务器,返回下一页的数据
        NSString *maxtime = responseObject[@"info"][@"maxtime"];
        self.maxtime=maxtime;
        
        NSMutableArray *array=responseObject[@"list"];
        
        //字典数组转模型数组
        NSMutableArray *topicsArray=[LZFTopicItem mj_objectArrayWithKeyValuesArray:array];
        
        //将新的数据加到
        [self.topicItemArray addObjectsFromArray:topicsArray];  //注意这里是追加到数据,而不是覆盖原来的数组
        
        //刷新表格
        [self.tableView reloadData];
        
        //结束尾部刷新
        [self endFooterFresh];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self endFooterFresh];
    }];
}

//结束尾部刷新
-(void)endFooterFresh
{
    self.footerFresh=NO;
    self.loadLabel.text=@"上拉加载更多数据....";
    self.loadLabel.backgroundColor=[UIColor redColor];
}




#pragma mark  tableviewdatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //没数据的话,tablefooterview不用显示
    self.tableView.tableFooterView.hidden=(self.topicItemArray.count==0);
    return self.topicItemArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZFTopicItem *topicItem=self.topicItemArray[indexPath.row];
    LZFTopicCell *topicCell=[tableView dequeueReusableCellWithIdentifier:ID];
    topicCell.topicItem=topicItem;
    return topicCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZFTopicItem *topicItem=self.topicItemArray[indexPath.row];
    return topicItem.rowHeight;
}



@end
